<template>
    <el-card class="prompt-card">
        <template #header>
            <div class="card-header">
                <h2>输入混搭提示</h2>
            </div>
        </template>

        <div class="prompt-groups">
            <div v-for="(group, index) in displayedPrompts" :key="index" class="prompt-group">
                <span class="prompt-index">{{ index + 1 }}.</span>
                <!-- 分类选择 -->
                <el-select v-model="group.category" placeholder="选择分类" style="width: 150px; margin-right: 10px;"
                    :loading="categoriesLoading" clearable @change="() => handleCategoryChange(index)"
                    :disabled="index > 0 && !isRowEnabled(index)">
                    <!-- 常规分类 -->
                    <el-option v-for="category in normalCategories" :key="category" :value="category" :label="category" />
                    <!-- 自定义分类（绿色） -->
                    <el-option key="自定义" value="自定义" label="自定义" class="custom-category-option">
                        <span class="custom-category">自定义</span>
                    </el-option>
                </el-select>

                <!-- 关键词输入框 -->
                <el-autocomplete v-model="group.text"
                    :fetch-suggestions="(query, cb) => querySearchAsync(query, cb, index)" 
                    placeholder="输入关键词"
                    style="flex-grow: 1; margin-right: 10px;" 
                    :disabled="!group.category || (index > 0 && !isRowEnabled(index))"
                    :trigger-on-focus="!isCustomCategory(group.category)"
                    popper-class="my-autocomplete"
                    @focus="handleFocus(index)"
                    @input="updateValue" 
                    :debounce="300">
                    <template #default="{ item }">
                        <div class="suggestion-item">
                            <div class="value">{{ item.value }}</div>
                        </div>
                    </template>
                </el-autocomplete>
                
                <!-- 时长选择器 - 仅在非自定义分类时显示 -->
                <div class="duration-selector" v-if="group.category && !isCustomCategory(group.category)">
                    <el-popover
                        placement="bottom"
                        :width="280"
                        trigger="click"
                        popper-class="duration-popover"
                    >
                        <template #reference>
                            <el-button 
                                size="default" 
                                :type="hasDuration(group) ? 'primary' : 'default'" 
                                :icon="Clock"
                                class="duration-button"
                            >
                                {{ formatDuration(group.duration) }}
                            </el-button>
                        </template>
                        
                        <div class="duration-picker">
                            <div class="duration-title">视频时长限制</div>
                            <div class="duration-inputs">
                                <el-input-number 
                                    v-model="group.duration.minutes" 
                                    :min="0"
                                    :max="999"
                                    controls-position="right"
                                    size="small"
                                    placeholder="分"
                                    @change="updateValue" 
                                />
                                <span class="duration-separator">:</span>
                                <el-input-number 
                                    v-model="group.duration.seconds" 
                                    :min="0"
                                    :max="59"
                                    controls-position="right"
                                    size="small"
                                    placeholder="秒"
                                    @change="updateValue" 
                                />
                            </div>
                            <div class="duration-actions">
                                <el-button size="small" type="danger" @click="clearDuration(group)">清除</el-button>
                            </div>
                        </div>
                    </el-popover>
                </div>
            </div>
        </div>

        <el-alert title="每行一个提示，系统会根据提示搜索视频并混合" type="info" :closable="false" style="margin: 15px 0;" />
    </el-card>
</template>

<script>
import { defineComponent, ref, computed, nextTick } from 'vue';
import mergeService from '@/services/mergeService';
import { Clock } from '@element-plus/icons-vue';

export default defineComponent({
    name: 'PromptInput',

    props: {
        modelValue: {
            type: Array,
            required: true
        },
        categories: {
            type: Array,
            default: () => []
        },
        categoriesLoading: {
            type: Boolean,
            default: false
        }
    },

    emits: ['update:modelValue'],

    setup(props, { emit }) {
        const keywordLoading = ref(false);
        const activeInputIndex = ref(-1); // 当前聚焦的输入框索引

        // 计算普通分类列表（不包括"自定义"）
        const normalCategories = computed(() => {
            return props.categories.filter(cat => cat !== '自定义');
        });

        // 检查是否为自定义分类
        const isCustomCategory = (category) => {
            return category === '自定义';
        };

        // 确保每个组的duration字段初始化
        const initializeDuration = () => {
            props.modelValue.forEach(group => {
                if (!group.duration) {
                    group.duration = { minutes: 0, seconds: 0 };
                }
            });
        };
        initializeDuration();

        // 计算要显示的行数（已填行 + 一个空行，最多显示5行）
        const displayedPrompts = computed(() => {
            let lastValidIndex = -1;

            // 查找最后一个有效行的索引
            for (let i = 0; i < props.modelValue.length; i++) {
                if (props.modelValue[i].category) {
                    lastValidIndex = i;
                }
            }

            // 确保所有显示的行都有duration字段
            const displayed = props.modelValue.slice(0, Math.min(lastValidIndex + 2, 5));
            displayed.forEach(group => {
                if (!group.duration) {
                    group.duration = { minutes: 0, seconds: 0 };
                }
            });
            return displayed;
        });

        // 检查行是否可用（只有前一行有category时，当前行才可用）
        const isRowEnabled = (index) => {
            if (index === 0) return true;
            return props.modelValue[index - 1]?.category ? true : false;
        };

        // 通知父组件值已更新
        const updateValue = () => {
            emit('update:modelValue', [...props.modelValue]);
        };

        // 处理分类变更
        const handleCategoryChange = (index) => {
            // 如果清空了分类，同时清空文本和时长
            if (!props.modelValue[index].category) {
                props.modelValue[index].text = '';
                props.modelValue[index].duration = { minutes: 0, seconds: 0 };
            }

            updateValue();
        };

        // 检查是否有设置时长
        const hasDuration = (group) => {
            if (!group.duration) return false;
            return group.duration.minutes > 0 || group.duration.seconds > 0;
        };

        // 格式化时长显示
        const formatDuration = (duration) => {
            if (!duration) return '时长';

            if (duration.minutes === 0 && duration.seconds === 0) {
                return '时长';
            }

            let result = '';
            if (duration.minutes > 0) {
                result += `${duration.minutes}分`;
            }
            if (duration.seconds > 0) {
                result += `${duration.seconds}秒`;
            }
            return result;
        };

        // 清除时长
        const clearDuration = (group) => {
            if (group.duration) {
                group.duration.minutes = 0;
                group.duration.seconds = 0;
                updateValue();
            }
        };

        // 处理输入框聚焦
        const handleFocus = (index) => {
            activeInputIndex.value = index;
        };

        // 获取关键词建议
        const querySearchAsync = (queryString, callback, index) => {

            // 获取当前行的分类
            const currentCategory = props.modelValue[index].category;

            if (!currentCategory || isCustomCategory(currentCategory)) {
                callback([]);
                return;
            }

            // 调用API获取关键词建议
            fetchKeywordSuggestions(queryString, currentCategory)
                .then(suggestions => {
                    nextTick(() => {
                        callback(suggestions);
                    });
                })
                .catch(() => {
                    callback([]);
                });
        };

        // 从API获取关键词建议
        const fetchKeywordSuggestions = async (query, category) => {
            if (keywordLoading.value) return [];

            try {
                keywordLoading.value = true;
                const response = await mergeService.getKeywordSuggestions(query || '', category);
                
                if (response.success && response.data && Array.isArray(response.data)) {
                    return response.data.map(item => {
                        if (typeof item === 'string') {
                            return { value: item };
                        }
                        return {
                            value: item.keyword || item.text || item.toString()
                        };
                    });
                }
                
                return [];
            } catch (error) {
                console.error('获取关键词建议失败:', error);
                return [];
            } finally {
                keywordLoading.value = false;
            }
        };

        return {
            updateValue,
            querySearchAsync,
            keywordLoading,
            displayedPrompts,
            isRowEnabled,
            handleCategoryChange,
            handleFocus,
            activeInputIndex,
            hasDuration,
            formatDuration,
            clearDuration,
            Clock,  // 图标
            normalCategories, // 普通分类列表
            isCustomCategory, // 判断是否为自定义分类
        };
    }
});
</script>

<style scoped>
.prompt-groups {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.prompt-group {
    display: flex;
    align-items: center;
}

.prompt-index {
    width: 25px;
    font-weight: bold;
}

.suggestion-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.suggestion-item .value {
    text-overflow: ellipsis;
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 自定义分类项样式 */
.custom-category {
    color: #67C23A;
    font-weight: bold;
}

:deep(.el-select-dropdown__item.custom-category-option.selected) {
    color: #67C23A;
}

/* 时长选择器样式 */
.duration-selector {
    margin-left: 5px;
    display: flex;
    align-items: center;
}

.duration-picker {
    padding: 15px;
}

.duration-title {
    font-weight: bold;
    margin-bottom: 10px;
    text-align: center;
}

.duration-inputs {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    gap: 10px;
}

.duration-inputs .el-input-number {
    width: 100px;
}

.duration-separator {
    font-size: 16px;
    font-weight: bold;
    margin: 0 4px;
}

.duration-actions {
    display: flex;
    justify-content: flex-end;
}

.duration-button {
    min-width: 80px;
}

/* 修复关键词输入框的样式 */
:deep(.el-autocomplete) {
    width: 100%;
}

:deep(.el-autocomplete-suggestion) {
    min-width: 200px !important;
}

:deep(.el-autocomplete-suggestion li) {
    padding: 8px 12px;
}

:deep(.my-autocomplete) {
    z-index: 3000 !important;
}
</style>